//
//  PaymentViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/11.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class PaymentViewController: UITableViewController, PopupDelegate, UIGestureRecognizerDelegate {
    var payChannel = 0
    var oneMonthPrice = 0.0
    var sixMonthsPrice = 0.0
    var oneYearPrice = 0.0
    var hud: MBProgressHUD?
    var paying = false
    
    @IBOutlet weak var sixMonthOldPriceLabel: UILabel!
    @IBOutlet weak var oneYearOldPriceLabel: UILabel!
    @IBOutlet weak var alipayCheckImg: UIImageView!
    @IBOutlet weak var weixinPayCheckImg: UIImageView!
    @IBOutlet weak var phonePayCheckImg: UIImageView!
    
    @IBOutlet weak var oneMonthLabel: UILabel!
    @IBOutlet weak var sixMonthsLabel: UILabel!
    @IBOutlet weak var oneYearLabel: UILabel!
    @IBOutlet weak var operaterLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("weixinPayHandler:"), name: StringUtils.WeipayNotification, object: nil)
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLBase(), parameters: nil, responseHandler: nil, netErrorHandler: nil, successHandler: initPrice, interErrorHandler: nil, jsonErrorHandler: nil)
    }
    
    override func viewDidDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: StringUtils.WeipayNotification, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backButtonPressed(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        
    }
    
    func setCheckImg(oldChannel: Int, newChannel: Int) {
        if (oldChannel != newChannel && newChannel >= 1 && newChannel <= 3) {
            switch (oldChannel) {
            case 1:
                self.alipayCheckImg.image = UIImage(named: "支付_21.png")
            case 2:
                self.weixinPayCheckImg.image = UIImage(named: "支付_21.png")
            case 3:
                self.phonePayCheckImg.image = UIImage(named: "支付_21.png")
            default:
                ()
            }
            
            switch (newChannel) {
            case 1:
                self.alipayCheckImg.image = UIImage(named: "支付_13.png")
                payChannel = 1
            case 2:
                self.weixinPayCheckImg.image = UIImage(named: "支付_13.png")
                payChannel = 2
            case 3:
                self.phonePayCheckImg.image = UIImage(named: "支付_13.png")
                payChannel = 3
            default:
                ()
            }
        }
        
    }
    
    func dismissPopup(animated: Bool) {
        if (self.popupViewController != nil) {
            self.dismissPopupViewControllerAnimated(animated, completion: nil)
            self.tableView.userInteractionEnabled = true
        }
        payChannel = 0
        self.phonePayCheckImg.image = UIImage(named: "支付_21.png")
    }
    
    //一个月VIP
    @IBAction func oneMonthVipButtonPressed(sender: AnyObject) {
        payOK(1)
    }
    
    //六个月VIP
    @IBAction func sixMonthVipButtonPressed(sender: AnyObject) {
        payOK(6)
    }
    
    //一年VIP
    @IBAction func oneYearVipButtonPressed(sender: AnyObject) {
        payOK(12)
    }
    
    func payOK(month: Int) {
        if (payChannel < 1 || payChannel > 2) {
            ViewUtils.popMessage(self, title: "注意", message: "请先选择支付方式")
            return
        }
        
        if (payChannel == 2 && !WXApi.isWXAppInstalled()) {
            ViewUtils.popMessage(self, title: "", message: "用户未安装微信客户端")
            return
        }
        
        startIndicator()
        let time: Int64 = Int64(NSDate().timeIntervalSince1970 * 1000)
        if (payChannel == 2) {
            var a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "month": month, "paychl": "SDK_WEIXIN", "timestamp": "\(time)", "device": "IPHONE"]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLBuyVip(), parameters: (a as! [String : AnyObject]), responseHandler: stopIndicator, netErrorHandler: netErrorHandler, successHandler: weixinPaySuccess, interErrorHandler: internalErrorHandler, jsonErrorHandler: jsonErrorHandler)
        } else if (payChannel == 1) {
            var a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "month": month, "paychl": "SDK_ALI", "timestamp": "\(time)", "device": "IPHONE"]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLBuyVip(), parameters: (a as! [String : AnyObject]), responseHandler: stopIndicator, netErrorHandler: netErrorHandler, successHandler: aliPaySuccess, interErrorHandler: internalErrorHandler, jsonErrorHandler: jsonErrorHandler)
        }
    }
    
    func setPrice(priceOri: Int, price: Int, cell: UITableViewCell, frame: CGRect) {
        if (priceOri == price) {
            var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 32, 18))
            label.text = "￥\(priceOri / 100)"
            let font = UIFont.systemFontOfSize(15 as CGFloat)
            label.font = font
            label.textColor = UIColor.orangeColor()
            let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
            cell?.addSubview(label)
        } else {
            var label1 = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 43, 17))
            label1.text = "￥\(priceOri / 100)"
            let font1 = UIFont.systemFontOfSize(14 as CGFloat)
            label1.font = font1
            label1.textColor = UIColor.lightGrayColor()
            cell.addSubview(label1)
            
            var str = label1.text
            var num = count(str!)
            let attr = NSMutableAttributedString(string: str!)
            attr.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(integer: 1), range: NSMakeRange(0, num))
            label1.attributedText = attr
            label1.sizeToFit()
            
            let frame2 = label1.frame
            var label2 = UILabel(frame: CGRectMake(frame2.origin.x + frame2.size.width, frame2.origin.y, 104, 21))
            label2.text = "立享优惠￥\(price / 100)"
            let font2 = UIFont.systemFontOfSize(13 as CGFloat)
            label2.font = font2
            label2.textColor = UIColor.redColor()
            cell.addSubview(label2)
        }
    }
    
    //MARK: - 网络回调函数
    
    func startIndicator() {
        hud = MBProgressHUD(view: self.view)
        self.view.addSubview(hud!)
        hud?.labelText = "处理中.."
        hud?.show(true)
    }
    
    func stopIndicator() {
        hud?.hide(false)
    }
    
    func netErrorHandler() {
        paying = false
        MBHudUtils.showText("网络错误", view: view)
    }
    
    func internalErrorHandler(retCode: Int, retMsg: String) {
        paying = false
        MBHudUtils.showText(retMsg, view: self.view)
    }
    
    func jsonErrorHandler() {
        paying = false
        MBHudUtils.showText("系统错误", view: self.view)
    }
    
    func aliPaySuccess(json: JSON) {
        paying = false
        var orderNo = json["orderno"].string
        var tranStr = json["transtr"].string
        var price = json["price"].int
        var notifyUrl = json["notifyurl"].string
        
        if let str = tranStr {
            AlipaySDK.defaultService().payOrder(str, fromScheme: "alipay2088021052551456", callback: { (ret: [NSObject : AnyObject]!) -> Void in
                let ret1 = ret as! [String: String]
                let retCode = ret1["resultStatus"]!
                
                if (retCode == "9000") {
                    self.navigationController?.popViewControllerAnimated(false)
                }
                ViewUtils.popMessage(self, title: "支付宝支付结果", message: StringUtils.alipayErrorCode[retCode]!)
                
            })
        }
    }
    
    func weixinPaySuccess(json: JSON) {
        paying = false
        var orderNo = json["orderno"].string
        var tranStr = json["transtr"].string
        var price = json["price"].int
        var notifyUrl = json["notifyurl"].string
        
        if let a = tranStr {
            let arr = StringUtils.splitTranStr(a)
            var request = PayReq()
            request.partnerId = arr["partnerid"]
            request.prepayId = arr["prepayid"]
            request.package = arr["package"]
            request.nonceStr = arr["noncestr"]
            request.timeStamp = UInt32(arr["timestamp"]!.toInt()!)
            request.sign = arr["sign"]
            WXApi.sendReq(request)
        }
    }
    
    func weixinPayHandler(notification: NSNotification) {
        let resp = notification.object as! BaseResp
        
        switch(resp.errCode) {
        case 0:
            self.navigationController?.popViewControllerAnimated(false)
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付成功")
        case -2:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "用户点击取消并返回")
        default:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付失败")
            
        }
    }
    
    func initPrice(data: JSON) {
        var title = data["title"].string
        var eversion = data["eversion"].string
        var showEversion = data["show_eversion"].string
        var customerPhone = data["customer_phone"].string
        var operaterAmt = data["operater_amt"].int
        var monthAmt1Ori = data["month_amt_1_ori"].int
        var monthAmt1 = data["month_amt_1"].int
        var monthAmt6Ori = data["month_amt_6_ori"].int
        var monthAmt6 = data["month_amt_6"].int
        var monthAmt12Ori = data["month_amt_12_ori"].int
        var monthAmt12 = data["month_amt_12"].int
        
        self.oneMonthPrice = Double(monthAmt1!) / 100.0
        self.sixMonthsPrice = Double(monthAmt6!) / 100.0
        self.oneYearPrice = Double(monthAmt12!) / 100.0
        
        self.setPrice(monthAmt1Ori!, price: monthAmt1!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 1))!, frame: self.oneMonthLabel.frame)
        self.setPrice(monthAmt6Ori!, price: monthAmt6!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 1))!, frame: self.sixMonthsLabel.frame)
        self.setPrice(monthAmt12Ori!, price: monthAmt12!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1))!, frame: self.oneYearLabel.frame)
        
        let frame = self.operaterLabel.frame
        var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 53, 18))
        label.text = "￥\(operaterAmt! / 100)/月"
        let font = UIFont.systemFontOfSize(15 as CGFloat)
        label.font = font
        label.textColor = UIColor.orangeColor()
        let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))
        cell?.addSubview(label)
    }
    

    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if (indexPath.section == 0) {
            setCheckImg(payChannel, newChannel: indexPath.row)
            if (indexPath.row == 3) {
                var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
                var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayCenter") as! PayCenterViewController
                viewController.delegate = self
                self.presentPopupViewController(viewController, animated: true, completion: nil)
                self.setPopviewGuesture()
                self.tableView.userInteractionEnabled = false
            }
        }
    }
    
    func setPopviewGuesture() {
        var fadeview = self.getBlueView()
        var tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismissPopup:"))
        tapRecognizer.numberOfTapsRequired = 1
        tapRecognizer.delegate = self
        fadeview.addGestureRecognizer(tapRecognizer)
    }

//    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//        // #warning Potentially incomplete method implementation.
//        // Return the number of sections.
//        return 0
//    }
//
//    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        // #warning Incomplete method implementation.
//        // Return the number of rows in the section.
//        return 0
//    }

    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
